package cz.apnetis.fitweb.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import cz.apnetis.fitweb.shared.Calorie;

public class CalorieListWidget extends Composite {

  private static CalorieListWidgetUiBinder uiBinder = GWT
      .create(CalorieListWidgetUiBinder.class);
  private final CalorieServiceAsync calorieService = GWT.create(CalorieService.class);

  interface CalorieListWidgetUiBinder extends
      UiBinder<Widget, CalorieListWidget> {
  }

  @UiField
  Button button;
  @UiField
  TextBox searchField;
  @UiField
  FlexTable table;

  public CalorieListWidget() {
    initWidget(uiBinder.createAndBindUi(this));
  }

  public void loadTableData() {
    calorieService.calorieList(searchField.getText(), new AsyncCallback<List<Calorie>>() {

      @Override
      public void onFailure(Throwable caught) {
        // TODO Auto-generated method stub
      }

      @Override
      public void onSuccess(List<Calorie> result) {
        table.clear();
        for (Calorie calorie : result) {
          int row = table.getRowCount();
          table.setWidget(row, 0, new Label(calorie.getName()));
          table.setWidget(row, 1, new Label(calorie.getCal().toString()));
          table.setWidget(row, 2, new Label(calorie.getJoule().toString()));
        }
      }
    });
  }

  @UiHandler("button")
  void onClick(ClickEvent e) {
    loadTableData();
  }
}
